from play import Controller, expose, Redirect
from models import User, Friend, UserAddForm, UserEditForm
import urlparse

import logging




class Main(Controller):

    def _before(self):
        if not self.session.has_key('user'):
            raise Redirect(Authentication.login, dict(super='man'))

    @expose(template="index.html")
    @expose(template="json")
    def index_html(self, name=None):
        """Use templateindex.html for rendering."""
        post_form=UserAddForm()
        return dict(name=name, post_form=post_form)

    @expose(template="index.html")
    @expose(template="json")
    def default(self, name=None):
        """Overriding default template."""
        self.use_template('custom.html')
        return dict(name=name)


    @expose(template="view_post.html")
    def add_post(self, title, content):
        post_form=UserEditForm(dict(title=title, content=content))
        
        logging.info("post_form.is_valid: "+str(post_form.is_valid()))
        logging.info("post_form.errors: "+str(type(post_form.errors)))
        logging.info("post_form.errors: "+str(post_form.errors.items()))
        raise Redirect(Main.index_html)
        
        #post=Post(title=title, content=content)
        #post.put()
        #key=str(post.key())
        #url=urlparse.urljoin(self.request.uri, key)
        #return dict(key=key, post=post, url=url)

    @expose(template="view_post.html")
    def view_post(self, key):
        post=User.get(key)
        logging.debug("post", post)
        url=urlparse.urljoin(self.request.uri, key)
        return dict(key=key, post=post, url=url)

    @expose(template="list_posts.html")
    def list_posts(self):
        logging.info("posts")
        posts=User.all()
        logging.info("posts: " + str(posts))
        return dict(posts=posts)



class Authentication(Controller):

    @expose(template="login.html")
    def login(self):
        return dict()

    @expose()
    def do_login(self, user):
        self.session['user'] = user
        raise Redirect(Main.index_html)

    @expose()
    def logout(self):
        self.session.clear()
        self.flash['message'] = 'You are now disconnected'
        raise Redirect(Authentication.login)



